package com.muki.spider.core;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class PackSpiderManager {
	
	private Map<String,SpiderFactory> works = new HashMap<>();
	private final Logger log = Logger.getLogger(PackSpiderManager.class);
	public static final Object signal = new Object();//线程间的通信变量
	
	@Autowired private UriGet get;
	
	@JmsListener(destination="theme")
	public void receive(Map<String,String> map) {
		String topic = map.getOrDefault("topic", null);
		String num_s = map.getOrDefault("num", "0");
		if(topic!=null) {
			log.info("获取到 {"+topic+"} 主题,系统创建爬虫数目:"+num_s);
			newWorkFactory(topic,Integer.parseInt(num_s));
		}
	}
	
	@JmsListener(destination="task")
	public void getTask(Map<String,String> map) {
		String topic = map.getOrDefault("topic", null);
		if(topic == null)
			return;
		String init_url = map.getOrDefault("init-url", null);
		if(init_url==null)
			return;
		if(SpiderUriMemoryCache.putIfAbsent(topic, init_url))
			get.doGet(topic,init_url,0);
		long delay = Long.valueOf(map.getOrDefault("delay", "1000"));
		int deep = Integer.valueOf(map.getOrDefault("time", "-1"));
		
		SpiderFactory factory = getWorkers(topic);
		if(factory==null) {
			log.info("no factory created");
			return;
		}
		Iterator<PackSpider> it = factory.iterator();
		log.info(topic+" "+init_url);
		while(it.hasNext()) {
			PackSpider pack = it.next();
			if(!pack.getBoolean("status")) {
				pack.put("topic",topic);
				pack.put("init-url", init_url);
				pack.put("delay", delay);
				pack.put("time", deep);
				pack.work();
			}
		}
	}
	
	/**
	 * 根据topic 创建Factory
	 * @param topic
	 * @param size
	 */
	public void newWorkFactory(String topic,int size) {
		SpiderFactory factory = new SpiderFactory(size);
		for(int i=0;i<size;i++) {
			factory.appendSpider(new PackSpider());
		}
		works.put(topic, factory);
	}
	
	public SpiderFactory getWorkers(String topic) {
		return works.getOrDefault(topic, null);
	}
	
	public boolean hasFactory(String topic) {
		return works.containsKey(topic);
	}
	
}
